package trss.dao.hibernate;


import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import trss.dao.TorrentDao;
import trss.model.Torrent;
import trss.model.User;
import trss.model.torrent.AnnounceList;
import trss.model.torrent.File;
import trss.model.torrent.Info;
import trss.model.torrent.MetaFile;



@Repository
public class TorrentDaoHibernate extends GenericDaoHibernate<Torrent, Long> implements TorrentDao {

    /**
     * Constructor to create a Generics-based version using Torrent as the entity
     */
    public TorrentDaoHibernate() {
        super(Torrent.class);
    }

    /**
    * ${@inheritDoc}
    */
    @Transactional
    public Torrent saveTorrent(Torrent torrent) {
        MetaFile meta = torrent.getMeta();
        List<AnnounceList> announseLists = meta.getAnnonceList();
        Info info = meta.getInfo();
        List<File> files = info.getFiles();
        for (File file : files) {
            getHibernateTemplate().saveOrUpdate(file);
        }
        for (AnnounceList announceList : announseLists) {
            getHibernateTemplate().saveOrUpdate(announceList);
        }
        getHibernateTemplate().saveOrUpdate(info);
        getHibernateTemplate().saveOrUpdate(meta);
        getHibernateTemplate().saveOrUpdate(torrent);
        getHibernateTemplate().flush();
        getHibernateTemplate().clear();
        return torrent;
    }

	/* (non-Javadoc)
	 * @see trss.dao.TorrentDao#get(trss.model.User, int)
	 */
	public List<Torrent> get(User user, int maxCount) {
		HibernateTemplate hibernateTemplate = getHibernateTemplate();
		if (maxCount > 0) {
			hibernateTemplate.setMaxResults(maxCount);
		}
		@SuppressWarnings("rawtypes")
		List rs = hibernateTemplate.find("from Torrent t where t.owner=?", user);
		List<Torrent> result = new ArrayList<Torrent>();
		for (Object object : rs) {
			Torrent t = (Torrent) object;
			result.add(t);
		}
		return result;
	}

}
